var grid;
$(document).ready(function() {
    initProcessTree();
    // initMainGrid(-1,-1);
    //产品线下拉框数据
    initProductList("lc_product_id");
});


$(document).on('show.bs.modal', '.modal', function(event) {
    $(this).appendTo($('body'));
}).on('shown.bs.modal', '.modal.in', function(event) {
    setModalsAndBackdropsOrder();
}).on('hidden.bs.modal', '.modal', function(event) {
    setModalsAndBackdropsOrder();
});

function setModalsAndBackdropsOrder() {
    var modalZIndex = 1040;
    $('.modal.in').each(function(index) {
        var $modal = $(this);
        modalZIndex++;
        $modal.css('zIndex', modalZIndex);
        $modal.next('.modal-backdrop.in').addClass('hidden').css('zIndex', modalZIndex - 1);
    });
    $('.modal.in:visible:last').focus().next('.modal-backdrop.in').removeClass('hidden');
}


function initMainGrid(domId,id) {
    $("#domId").val(domId);
    $("#hid").val(id);
    /////////////jehc扩展属性目的可方便使用（boot.js文件datatablesCallBack方法使用） 如弹窗分页查找根据条件 可能此时的form发生变化 此时 可以解决该类问题
    var opt = {
        searchformId:'searchForm'
    };
    var options = DataTablesPaging.pagingOptions({
        ajax:function (data, callback, settings){datatablesCallBack(data, callback, settings,workflowModules+'/lcDeploymentHis/list',opt);},//渲染数据
        //在第一位置追加序列号
        fnRowCallback:function(nRow, aData, iDisplayIndex){
            jQuery('td:eq(0)', nRow).html(iDisplayIndex +1);
            return nRow;
        },
        order:[],//取消默认排序查询,否则复选框一列会出现小箭头
        tableHeight:reGetBodyHeight()*0.5+'px',
        sPaginationType:'simple_numbers',
        pageLength:5,
        //列表表头字段
        colums:[
            {
                data:"id",
                width:"50px"
            },
            {
                data:"id",
                render:function(data, type, row, meta) {
                    var id = row.id;
                    var lc_process_title = row.lc_process_title;
                    var btn = '<div class="btn-group ml-2">'+
                        '<button type="button" class="btn btn-light-primary font-weight-bold"><i class="fa fa-magic fa-lg"></i><span>操作</button>'+
                        '<button type="button" class="btn btn-light-primary font-weight-bold dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">'+
                        '<span class="sr-only"></span>'+
                        '</button>'+
                        '<div class="dropdown-menu" style="">'+
                        '<a class="dropdown-item" href=javascript:toDeploymentHisDetail("'+data+'")>基本信息</a>'+
                        '<a class="dropdown-item" href=javascript:showDeploymentHisImage("'+data+'")>流程图</a>'+
                        '<div class="dropdown-divider"></div>'+
                        // '<a class="dropdown-item" href="javascript:initNodeDatables('+id+','+lc_process_title+')">流程节点</a>'+
                        '<a class="dropdown-item" href=javascript:toDeploymentHisDetail("'+data+'")>全局设置</a>'+
                        '</div>'+
                        '</div>';
                    return btn;
                }
            },
            {
                data:"lc_deployment_his_id",
                width:"100px"
            },
            {
                data:'lc_deployment_his_name',
                width:"50px"
            },
            {
                data:'lc_deployment_his_time',
                width:"50px",
                render:function(data, type, row, meta) {
                    return dateformat(data);
                }
            },
            {
                data:'version',
                width:"50px"
            },
            {
                data:'lc_deployment_his_status',
                width:"50px",
                render:function(data, type, row, meta) {
                    if(data == 0){
                        return "发布中";
                    }
                    if(data == 1){
                        return "已关闭";
                    }else{
                        return "缺省";
                    }
                }
            },
            {
                data:"name",
                width:"120px"
            },
            {
                data:"groupName",
                width:"120px"
            }
        ]
    });
    grid=$('#datatables').dataTable(options);
    //实现单击行选中
    clickrowselected('datatables');
    //废弃
    // var  table = $('#datatables') .DataTable();
    // $('#datatables tbody').on('click', 'tr', function () {
    //     var  data = table.row(this).data();
    //     initNodeDatables(data.id,data.lc_process_title);
    // });
    // initNodeDatables("-1","");
}

/**
 *
 */
function initProcessTree() {
    initNodeDatables("-1","","2");
    if ($('#processTree').jstree()) {//判断是否已有实例
        $('#processTree').jstree().destroy();//销毁实例
    };
    ajaxBRequestCallFn( workflowModules + "/lcProcess/tree?lc_process_title="+$("#lc_process_title").val()+"&lc_process_status="+$("#lc_process_status").val()+"&lc_product_id="+$("#lc_product_id").val()+"&lc_group_id="+$("#lc_group_id").val(),{},function(result){
        if(undefined == result.data || null == result.data || "" == result.data){
            $("#processTree").html("暂无数据！");
        }else{
            // data = result.data;
            var data=eval("("+result.data+")");
            $('#processTree').jstree({ "types" : {
                    //////////样式一///////////
                    // "default" : {
                    //     "icon" : "fa fa-folder"
                    // },
                    // "file" : {
                    //     "icon" : "fa fa-file"
                    // }
                    ///////样式二///////////
                    // "default" : {
                    //     "icon" : "fa fa-folder m--font-warning"
                    // },
                    // "file" : {
                    //     "icon" : "fa fa-file  m--font-warning"
                    // }
                    ///////样式三///////////
                    "default" : {
                        "icon" : "fa flaticon-envelope m--font-success"
                    },
                    "file" : {
                        "icon" : "fa fa-folder m--font-danger"
                    }
                    ///////样式四///////////
                    // "default" : {
                    //     "icon" : "fa fa-folder m--font-brand"
                    // },
                    // "file" : {
                    //     "icon" : "fa fa-file  m--font-warning"
                    // }
                    // /////样式五///////////
                    // "default" : {
                    //     "icon" : "fa fa-folder m--font-brand"
                    // },
                    // "file" : {
                    //     "icon" : "fa fa-file  m--font-brand"
                    // }
                    // /////样式六///////////
                    // "default" : {
                    //     "icon" : "fa fa-folder m--font-success"
                    // },
                    // "file" : {
                    //     "icon" : "fa fa-file  m--font-success"
                    // }
                },
                "animation" : 10,
                "state" : { "key" : "demo2" },
                // "plugins" : ["wholerow","contextmenu","dnd", "state", "types","search"],//wholerow显示连线
                "plugins" : ["wholerow","contextmenu","dnd", "state", "types","search"],//wholerow显示连线
                'core' : {
                    "themes" : {
                        "responsive": false,
                        "stripes":false,//隔行变色
                        "ellipsis": true //节点名过长时是否显示省略号。
                    },
                    'data' : data,
                    "multiple" : false
                },
                "contextmenu": {
                    items: {
                        add: {
                            "label": "流程信息",
                            "icon": "fa flaticon-list",
                            "action": function (data) {
                                var inst = jQuery.jstree.reference(data.reference);
                                data = inst.get_node(data.reference);
                                var domId = data.id;
                                var type = data.original.tempObject;
                                var text = data.text;
                                if(type == "C"){
                                    toDeploymentHisDetail(domId);
                                }
                                if(type == "P"){
                                    initProcess(domId);
                                }
                            }
                        }
                        ,
                        "edit": {
                            "label": "流程图",
                            "icon": "la la-file-image-o",
                            "action": function (data) {
                                var inst = jQuery.jstree.reference(data.reference);
                                data = inst.get_node(data.reference);
                                var domId = data.id;
                                var type = data.original.tempObject;
                                var text = data.text;
                                if(type == "C"){
                                    showDeploymentHisImage(domId,2,text);
                                }
                                if(type == "P"){
                                    showDeploymentHisImage(domId,1,text);
                                }
                            }
                        },
                        "del": {
                            "label": "流程节点",
                            "icon": "fa flaticon-interface-9",
                            "action": function (data) {
                                var inst = jQuery.jstree.reference(data.reference);
                                data = inst.get_node(data.reference);
                                var domId = data.id;
                                var type = data.original.tempObject;
                                var text = data.text;
                                if(type == "C"){
                                    initNodeDatables(domId,text,2);
                                    // initMainGrid("",domId);
                                }
                                if(type == "P"){
                                    initNodeDatables(domId,"",1);
                                }
                            }
                        }
                    }
                }
            }).on('changed.jstree',function(e,data){
                // //当前选中节点的id
                // console.log(data.instance.get_node(data.selected[0]).id);
                // console.log(data.instance.get_node(data.selected[0]).original.tempObject);
                // var domId = data.instance.get_node(data.selected[0]).id;
                // var type = data.instance.get_node(data.selected[0]).original.tempObject;
                // //当前选中节点的文本值
                // console.log(data.instance.get_node(data.selected[0]).text);
                // var text = data.instance.get_node(data.selected[0]).text;
                // if(type == "C"){
                //     initNodeDatables(domId,text,2);
                //     initMainGrid("",domId);
                // }else{
                //     initNodeDatables("-1","",1);
                // }
                // if(type == "P"){
                //     initMainGrid(domId);
                // }
            }).on('select_node.jstree',function(e,data){

                /*选中之后触发*/
            }).on(' deselect_node.jstree',function(e,data){
                /*取消选中触发*/
            }).on("loaded.jstree", function (event, data) {
                data.instance.clear_state();/*此句用来清除之前选中的数据不可以去掉*/
                // data.instance.open_all(-1); // -1 打开所有节点
                data.instance.open_all(2); // -1 打开所有节点
                // $('#orgTree').jstree().open_all();/*初始化打开树，对于复选框。 不展开的话，如果下面有逻辑选择则会有问题*/
                // //选择指定节点
                // var tempIds = $("#ids").val();
                // var tempIdsArr = tempIds.split(",");
                // $.each(TempIdsArr,function(index,value){
                //     var id=value;
                //     $('#orgTree').jstree('select_node',id,true,true);/*选中id对应的节点*/
                // });
            }).on("load_node.jstree",function(event,data){
                /*加载node时候触发*/
            });
        }
    });
}

/**
 *
 * @param lc_deployment_his_id
 */
function initNodeDatables(id,lc_process_title,type) {
    var url = workflowModules+'/lcDeploymentHis/userTasks/'+id;
    if(type ==  1){//主流程类型
        url = workflowModules+'/lcProcess/userTasks/'+id;
    }
    var opt = {
        searchformId:'searchFormlcNodeAttribute'
    };
    var options = DataTablesList.listOptions({
        ajax:function (data, callback, settings){datatablesListCallBack(data, callback, settings,url,opt);},//渲染数据
        //在第一位置追加序列号
        fnRowCallback:function(nRow, aData, iDisplayIndex){
            jQuery('td:eq(0)', nRow).html(iDisplayIndex+1);
            return nRow;
        },
        order:[],//取消默认排序查询,否则复选框一列会出现小箭头
        tableHeight:datatablesDefaultHeight+100,
        //列表表头字段
        colums:[
            {
                data:"nodeId",
                width:"50px"
            },
            {
                data:'nodeName'
            },
            {
                data:'mutil',
                render:function(data, type, row, meta) {
                    if(data == 20){
                        return "<span class='m-badge m-badge--info'>是</span>"
                    }
                    return "<span class='m-badge m-badge--metal'>否</span>"
                }
            },
            {
                data:'nodeType',
                render:function(data, type, row, meta) {
                    if( data== "END"){
                        return "结束节点";
                    }else if( data== "userTask"){
                        return "用户节点";
                    }else{
                        return "缺省";
                    }
                }
            },
            {
                data:'initiator',
                render:function(data, type, row, meta) {
                    if(data == 20){
                        return "<span class='m-badge m-badge--info'>是</span>"
                    }
                    return "<span class='m-badge m-badge--metal'>否</span>"
                }
            },
            {
                data:'lc_node_attribute_id',
                render:function(data, type, row, meta) {
                    var nodeType = row.nodeType;
                    if(nodeType == "userTask"){
                        if( data== null || data == ''){
                            return "<span class='label label-lg font-weight-bold label-light-danger label-inline'>未设定</span>";
                        }else{
                            return "<span class='label label-lg font-weight-bold label-light-primary label-inline'>已设定</span>";
                        }
                    }else{
                        return "";
                    }
                }
            },
            {
                data:'nodeId'
            },
            {
                data:'orderNumber'
            },
            {
                data:"nodeId",
                render:function(data, type, row, meta) {
                    var mounts_id = row.mounts_id;//挂载编号
                    var hid_ = row.hid_;//发布历史版本id
                    var nodeName = row.nodeName;//节点名称
                    var nodeId = row.nodeId;//节点id
                    var notice_type = row.notice_type;
                    var lc_process_id = row.lc_process_id;
                    var attributeKey = row.attributeKey;
                    var lc_process_title = row.lc_process_title;
                    var mutil = row.mutil;
                    var nodeType = row.nodeType;
                    if(nodeType == "userTask"){
                        var btn = '<button class="btn btn-light-primary font-weight-bold mr-1" onclick=initNodeAttribute(\"'+hid_+'\",\"'+lc_process_title+'\",\"'+nodeId+'\",\"'+nodeName+'\",\"'+lc_process_id+'\",\"'+mounts_id+'\",\"'+mutil+'\")><i class="fa flaticon-interface-9"></i>节点规则</button>';
                        return btn;
                    }else{
                        return "";
                    }
                }
            }
        ]
    });
    grid=$('#nodeDatatables').dataTable(options);
    //实现单击行选中
    clickrowselected('nodeDatatables');
    //产品线下拉框数据
    // initProductList("lc_product_id");
}


/**
 * 流程图
 * @param id
 */
function showDeploymentHisImage(id,type,title) {
    var ImageModalCount = 0 ;
    $('#lcDeploymentHisImagePanelBody').height(reGetBodyHeight()-128);

    $('#lcDeploymentHisImageModalLabel').html("流程图-"+title);
    $('#lcDeploymentHisImageModal').modal({backdrop:'static',keyboard:false});
    $('#lcDeploymentHisImageModal').modal({"backdrop":"static"}).modal('show').on("shown.bs.modal",function(){
        var $modal_dialog = $("#lcDeploymentHisImageModalDialog");
        $modal_dialog.css({'margin': 0 + 'px auto'});
        $modal_dialog.css({'width':reGetBodyWidth()+'px'});
        if(++ImageModalCount == 1) {
            //加载表单数据
            if(type == 1){
                ajaxBRequestCallFn(workflowModules+'/lcProcess/image/base64/'+id,{},function(result){
                    $('#imagePath').attr("src", result.data);
                });
            }
            if(type == 2){
                ajaxBRequestCallFn(workflowModules+'/lcDeploymentHis/image/base64/'+id,{},function(result){
                    $('#imagePath').attr("src", result.data);
                });
            }

        }
    });
}


/**
 * 流程发布版本记录详情
 * @param lc_process_id
 * @param lc_process_title
 */
function toDeploymentHisDetail(id){
    $('#lcDeploymentHisDetailBody').height(reGetBodyHeight()*0.5);
    $('#lcDeploymentHisDetailModal').modal({backdrop:'static',keyboard:false});
    $('#lcDeploymentHisDetailModal').modal({"backdrop":"static"}).modal('show').on("shown.bs.modal",function(){
        // 是弹出框居中。。。
        var $modal_dialog = $("#lcDeploymentHisDetailModalDialog");
        $modal_dialog.css({'width':reGetBodyWidth()*0.5+'px'});
        //加载表单数据
        ajaxBRequestCallFn(workflowModules+'/lcDeploymentHis/get/'+id,{},function(result){
            $('#lc_deployment_his_id').val(result.data.lc_deployment_his_id);
            $('#lc_deployment_his_name').val(result.data.lc_deployment_his_name);
            $('#lc_deployment_his_time').val(dateformat(result.data.lc_deployment_his_time));
            $('#lc_deployment_his_tenantId').val(result.data.lc_deployment_his_tenantId);
            $('#lc_deployment_his_status').html(result.data.lc_deployment_his_status==0?"<font color='#008b8b'>【运行中】</font>":"<font color='#8b0000'>【关闭】</font>");
            $('#uid').val(result.data.uid);
            $('#uk').val(result.data.uk);
            var lc_process_flag = result.data.lc_process_flag;
            if(lc_process_flag == 0){
                $('#lc_process_flag').val("通过平台设计器设计");
            }
            if(lc_process_flag == 1){
                $('#lc_process_flag').val("通过上传部署");
            }
            $('#name').val(result.data.name);
            $('#groupName').val(result.data.groupName);
            $('#w').val(result.data.w);
            $('#h').val(result.data.h);
        });
    });
}

